package x.mybatis.metadata;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Field;

/**
 * JPA 注解解析器
 *
 * @author hanjuntao
 * @date 2025/5/8 0008
 */
public class JpaAnnotationParser {
    private JpaAnnotationParser() {
    }

    public static TableMetadata parse(Class<?> entityClass) {
        TableMetadata tableMetadata = new TableMetadata();
        tableMetadata.setEntityClass(entityClass);

        // 解析表名
        Table tableAnnotation = entityClass.getAnnotation(Table.class);
        if (tableAnnotation != null && !tableAnnotation.name().isEmpty()) {
            tableMetadata.setTableName(tableAnnotation.name());
        } else {
            // 默认表名（驼峰转下划线）
            tableMetadata.setTableName(camelToUnderline(entityClass.getSimpleName()));
        }

        // 解析字段
        for (Field field : entityClass.getDeclaredFields()) {
            Column columnAnnotation = field.getAnnotation(Column.class);
            if (columnAnnotation == null) {
                continue; // 忽略无 @Column 注解的字段
            }

            ColumnMetadata column = new ColumnMetadata();
            column.setFieldName(field.getName());
            column.setJavaType(field.getType());

            // 解析列名
            if (!columnAnnotation.name().isEmpty()) {
                column.setColumnName(columnAnnotation.name());
            } else {
                column.setColumnName(camelToUnderline(field.getName()));
            }

            // 检查是否为主键
            boolean isPrimaryKey = field.isAnnotationPresent(Id.class);
            column.setPrimaryKey(isPrimaryKey);

            tableMetadata.getColumns().add(column);
        }

        TableMetadataHolder.put(entityClass, tableMetadata);

        return tableMetadata;
    }

    /**
     * 驼峰转下划线
     */
    private static String camelToUnderline(String str) {
        return str.replaceAll("([a-z0-9])([A-Z])", "$1_$2").toLowerCase();
    }
}
